package com.shuyu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shuyu.common.exception.ServiceException;
import com.shuyu.common.utils.StringUtils;
import com.shuyu.domain.NFT;
import com.shuyu.domain.Product;
import com.shuyu.domain.ProductCardCode;
import com.shuyu.mapper.NFTMapper;
import com.shuyu.service.NFTService;
import com.shuyu.service.NftTransferService;
import com.shuyu.service.ProductCardCodeService;
import com.shuyu.service.ProductService;
import com.shuyu.vo.CardVo;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class NFTServiceImpl extends ServiceImpl<NFTMapper, NFT> implements NFTService {
    @Resource
    private ProductService productService;
    @Resource
    private NftTransferService nftTransferService;
    @Resource
    private ProductCardCodeService productCardCodeService;
    @Resource
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    @Resource
    private NFTService nftService;
//    @Override
//    public void createNFT(int productId) {
//        threadPoolTaskExecutor.execute(new CreateNFTHandler(productId));
//    }

    @Override
    public String importCard(List<CardVo> cardList, int id, String operName) {

        if (StringUtils.isNull(cardList) || cardList.size() == 0)
        {
            throw new ServiceException("导入卡牌数据不能为空！");
        }
        Product u = productService.getById(id);
        if (StringUtils.isNull(u))
        {
            throw new ServiceException("卡牌ID不存在存在");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (CardVo cardVo : cardList)
        {
            try
            {
                productCardCodeService.remove(new LambdaQueryWrapper<ProductCardCode>().eq(ProductCardCode::getTransactionHash,cardVo.getTransactionHash()));
                String transactionHash = cardVo.getTransactionHash();
                NFT nft = nftService.getOne(new LambdaQueryWrapper<NFT>().eq(NFT::getTransactionHash, transactionHash));
                Integer nftId = null;
                if(nft != null){
                    nftId = nft.getId();
                }
                ProductCardCode productCardCode = new ProductCardCode(id, cardVo.getCardSerial()+cardVo.getSerial(), transactionHash, 0, new Date(), nftId);
                productCardCodeService.save(productCardCode);
                successNum++;
                successMsg.append("<br/>" + successNum + "、序号 " + cardVo.getIndex() + " 保存成功");
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、序号 " + cardVo.getIndex() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public List<NFT> getNFTList(Integer productId) {
        return this.baseMapper.getNFTList(productId);
    }

//    class CreateNFTHandler implements Runnable {
//
//        private int productId;
//
//        public CreateNFTHandler(int productId) {
//            this.productId = productId;
//        }
//
//        @Override
//        public void run() {
//            //铸造NFT
//            try {
//                Product product = productService.getById(productId);
//                int quantity = product.getQuantity();
//                for (int i = 1; i <= quantity; i++) {
//                    MetadataVo metadata = new MetadataVo(i+"",product.getName()+"#"+i,product.getImg(),product.getIntroduction(), product.getIssuingCompany(),
//                            product.getProductionCompany());
//                    String metadataString = JSONObject.from(metadata).toString();
//                    String contractAddress = product.getContractAddress();
//                    if(StringUtils.isEmpty(contractAddress)){
//                        contractAddress = Constants.CONTRACT_ADDRESS;
//                    }
//                    NFTVo nftVo = NFTUtils.createNFT(metadataString,contractAddress);
//                    String collectionCode = Md5Utils.hash(nftVo.getTokenId().toString()+"didol"+productId);
//                    NFT nft = new NFT(productId, nftVo.getTransactionHash(), nftVo.getTokenId(), collectionCode, Constants.WALLET_ADDRESS, new Date());
//                    save(nft);
//                    NftTransfer nftTransfer = new NftTransfer(nft.getId(), nftVo.getTransactionHash(), nft.getTokenId(), Constants.INIT_WALLET_ADDRESS, Constants.WALLET_ADDRESS, "minting", new Date(),"数与（杭州）文化科技有限公司");
//                    nftTransferService.save(nftTransfer);
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//                throw new RuntimeException(e);
//            }
//        }
//    }

}
